package cn.itcast.itcaststore.dao.impl;

import cn.itcast.itcaststore.dao.NoticeDao;
import cn.itcast.itcaststore.domain.Notice;
import cn.itcast.itcaststore.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**用户
 * @Auther: 万秋泊
 * @Date: 2021/10/27 10:55
 * @Description:
 * 商家
 * 王之伟
 *
 */
public class NoticeDaoImpl implements NoticeDao {
    private QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());

    @Override
    public Notice getRecentNotice() {
        String sql = "select * from notice order by n_time desc limit 0,1";
        Notice notice = null;
        try {
            notice = runner.query(sql, new BeanHandler<Notice>(Notice.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return notice;
    }

    /**
     * 查询所有公告
     * @Auther:王之伟
     * @throws SQLException
     */

    @Override
    public List<Notice> findAllNotice() throws SQLException {
        //写sql语句
        String sql = "select * from notice";
        return runner.query(sql, new BeanListHandler<Notice>(Notice.class));
    }

    /**
     * 添加公告
     * @param notice
     * @Auther:王之伟
     * @throws SQLException
     */
    @Override
    public int addNotice(Notice notice) throws SQLException {
        //写sql语句
        String sql = "insert into notice(title,details,n_time) values(?,?,?)";
        //调用方法
        return runner.update(sql,notice.getTitle(),notice.getDetails(),notice.getN_time());
    }

    /**
     * 删除公告
     * @Auther:王之伟
     * @param n_id
     * @throws SQLException
     */
    @Override
    public void deleteNotice(int n_id) throws SQLException {
        //写sql语句
        String sql = "delete from notice where n_id = ?";
        //创建QueryRunner对象
        runner.update(sql, n_id);
    }

    /**
     * 更改
     * @Auther:王之伟
     * @param notice
     * @throws SQLException
     */

    @Override
    public void updateNotice(Notice notice) throws SQLException {
        String sql = "update notice set title=?,details=?,n_time=? where n_id=?";
        runner.update(sql, notice.getTitle(),notice.getDetails(),notice.getN_time(),notice.getN_id());
    }


    /**
     * 根据id查
     * @Auther:王之伟
     * @param n_id
     * @return
     * @throws SQLException
     */
    @Override
    public Notice findNoticeById(int n_id) throws SQLException {
        String sql = "select * from notice where n_id = ?";
        return runner.query(sql, new BeanHandler<Notice>(Notice.class),n_id);
    }


}
